#include "TeamManager.h"
#include "NameManager.h"
#include "ServiceProvider.h"
#include "GameSettings.h"

#include <algorithm>
#include <functional>
#include <cassert>

size_t TeamManager::NUMBERS_OF_TEAMS = 0;

TeamManager::TeamManager(ServiceProvider* const i_sp)
:m_sp(i_sp)
{
	assert(i_sp);
}

TeamManager::~TeamManager()
{
	Clear();
}

void TeamManager::Clear()
{
	Utilities::DeepClear(m_teams);

	NUMBERS_OF_TEAMS = 0;
}

void TeamManager::Initialize(const size_t i_startID)
{
	NUMBERS_OF_TEAMS			= i_startID;

	Team::s_params.MAX_CHAR_TEAM_NAME = m_sp->GetSettings().GetValue("I_MAX_CHAR_TEAM_NAME").Get<size_t>();
	Team::s_params.STARTING_TEAM_PLAYERS = m_sp->GetSettings().GetValue("I_STARTING_TEAM_PLAYERS").Get<size_t>();
	Team::s_params.MAX_TEAM_PLAYERS		= m_sp->GetSettings().GetValue("I_MAX_TEAM_PLAYERS").Get<size_t>();
	Team::s_params.MIN_TEAM_PLAYERS		= m_sp->GetSettings().GetValue("I_MIN_TEAM_PLAYERS").Get<size_t>();

	Team::s_params.TITOLARS_GOALKEEPERS	= m_sp->GetSettings().GetValue("I_TITOLARS_GOALKEEPERS").Get<size_t>();
	Team::s_params.TITOLARS_DEFENDERS	= m_sp->GetSettings().GetValue("I_TITOLARS_DEFENDERS").Get<size_t>();
	Team::s_params.TITOLARS_ATTACKERS	= m_sp->GetSettings().GetValue("I_TITOLARS_ATTACKERS").Get<size_t>();
	Team::s_params.TITOLARS_PLAYERS		= Team::s_params.TITOLARS_GOALKEEPERS + 
											Team::s_params.TITOLARS_DEFENDERS + 
											Team::s_params.TITOLARS_ATTACKERS;
}

Team* TeamManager::GetNewTeam()
{
	Team* newTeam = new Team(m_sp, m_sp->GetNameMgr().GetATeamName(), GetNewID());
	m_teams.push_back(newTeam);
	return newTeam;
}

/*Team* TeamManager::GetNewEmptyTeam()
{
	Team* newTeam = new Team(m_sp);
	m_teams.push_back(newTeam);
	return newTeam;
}*/

struct FindID
{
	FindID(size_t i_id) : m_id(i_id) {}
	bool operator()(const Team* const i_team) const
	{
		return i_team->GetID() == m_id;
	}
	size_t m_id;
};

Team* TeamManager::GetTeamFromID(size_t i_teamID)
{
	TeamVecIt it = std::find_if(m_teams.begin(), m_teams.end(), FindID(i_teamID));

	if(it == m_teams.end())
	{
		assert(false);
		return NULL;
	}
	else
		return *it;
}